#!/bin/bash
#========================================================================
# Author: YSLin
# Email: 
# File Name: timer.sh
# Description: 
#    there are critical sections where commands that require a large amount of time to complete
#	 are executed. On rare occasions, these commands might not finish processing. In order to deal with this
#	 situation, you need to set up a timer within the script. When the timer expires, you should terminate the
#	 program and inform the user about the abnormal exit.
#    1. Set a handler for the ALARM signal.
#	 2. Set the timer.
#	 3. Execute the program.
#	 4. Wait for the program to finish executing.
#	 5. Unset the timer.

# Edit History: 
#   2011-01-21    File created.
#========================================================================
AlarmHandler() {
	echo "Got SIGALARM, cmd took too long."
	KillSubProcs
	exit 14
}
KillSubProcs() {
	kill ${CHPROCIDS:-$!}
	if [ $? -eq 0 ] ; then echo "Sub-processes killed." ; fi
}
SetTimer() {
	DEF_TOUT=${1:-10};
	if [ $DEF_TOUT -ne 0 ] ; then
		sleep $DEF_TOUT && kill -s 14 $$ &
		CHPROCIDS="$CHPROCIDS $!"
		TIMERPROC=$!
	fi
}
UnsetTimer() {
	kill $TIMERPROC
}
# main()
if [ $# -lt 1 ] ; then
	echo "USAGE: `basename $0` infiniteloop.sh"
	exit 0
fi

trap AlarmHandler 14
SetTimer 15
PROG=$1
./$PROG &
CHPROCIDS="$CHPROCIDS $!"
wait $!
UnsetTimer
echo "All Done."
exit 0
